﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Data;
using System.ComponentModel;
using EIA.Basic.Model;
using EIA.WCFService.AuthProxy;

namespace EIA.SLClient.ProjectManage
{
    public class LoginViewModel : SimpleMvvmToolkit.ViewModelBase<LoginViewModel>
    {
        public const string COOKIES_KEY_REMEMBER_LOGINID = "eia_cookies_rember_login_id";
        public const string COOKIES_KEY_REMEMBER_SESSION = "eia_cookies_rember_session";
        public const string COOKIES_KEY_LOGINID = "eia_cookies_login_id";

        public LoginViewModel()
        {
#if DEBUG
            Utility.CookiesUtils.SetCookie(EIA.WCFService.ClientProxy.ProxyBase.TOKEN_COOKIE_KEY, "2c9119df-82eb-46b1-ba89-39398e1e6121");
#endif
            IsShow = true;
            if (IsInDesignMode)
            {
                IsShow = true;
                return;
            }

            RememberLoginId = Utility.CookiesUtils.GetCookie(COOKIES_KEY_REMEMBER_LOGINID) == true.ToString();
            RememberSession = Utility.CookiesUtils.GetCookie(COOKIES_KEY_REMEMBER_SESSION) == true.ToString();
            if (RememberLoginId) LoginId = Utility.CookiesUtils.GetCookie(COOKIES_KEY_LOGINID);

            RegisterToReceiveMessages(EIA.SLClient.ProjectManage.Infrastructure.MessageTokens.LOGIN_HIDE, EP_LoginHide);
            RegisterToReceiveMessages(EIA.SLClient.ProjectManage.Infrastructure.MessageTokens.LOGIN_SHOW, EP_LoginShow);
            RegisterToReceiveMessages<object, TStaff>(EIA.SLClient.ProjectManage.Infrastructure.MessageTokens.LOGIN_STAFF_CURRENT, EP_LoginStaffCurrent);
            IdentifyLoginStaff();
        }
        private void EP_LoginHide(object sender, SimpleMvvmToolkit.NotificationEventArgs e)
        {
            IsShow = false;
        }
        private void EP_LoginShow(object sender, SimpleMvvmToolkit.NotificationEventArgs e)
        {
            IsShow = true;
        }
        private void EP_LoginStaffCurrent(object sender, SimpleMvvmToolkit.NotificationEventArgs<object, TStaff> e)
        {
            if (e != null && e.Completed != null)
            {
                e.Completed(LoginedStaff);
            }
        }

        private void Busy(string msg = "等待...")
        {
            IsBusy = true;
            SendMessage<bool>(EIA.SLClient.ProjectManage.Infrastructure.MessageTokens.BUSY_STATE, new SimpleMvvmToolkit.NotificationEventArgs<bool>(msg, true));
        }

        private void Free()
        {
            IsBusy = false;
            SendMessage<bool>(EIA.SLClient.ProjectManage.Infrastructure.MessageTokens.BUSY_STATE, new SimpleMvvmToolkit.NotificationEventArgs<bool>("", false));
        }

        #region notifyprop

        protected bool _IsBusy;
        /// <summary>
        /// 
        /// </summary>
        public bool IsBusy
        {
            get { return _IsBusy; }
            set
            {
                _IsBusy = value;
                NotifyPropertyChanged(m => m.IsBusy);
            }
        }

        protected bool _IsShow;
        /// <summary>
        /// 注释
        /// </summary>
        public bool IsShow
        {
            get { return _IsShow; }
            set
            {
                _IsShow = value;
                NotifyPropertyChanged(m => m.IsShow);
            }
        }

        protected TStaff _LoginedStaff;
        /// <summary>
        /// 注释
        /// </summary>
        public TStaff LoginedStaff
        {
            get { return _LoginedStaff; }
            set
            {
                _LoginedStaff = value;
                NotifyPropertyChanged(m => m.LoginedStaff);
            }
        }


        protected string _LoginId;
        /// <summary>
        /// 注释
        /// </summary>
        public string LoginId
        {
            get { return _LoginId; }
            set
            {
                _LoginId = value;
                NotifyPropertyChanged(m => m.LoginId);
            }
        }

        protected string _Password;
        /// <summary>
        /// 注释
        /// </summary>
        public string Password
        {
            get { return _Password; }
            set
            {
                _Password = value;
                NotifyPropertyChanged(m => m.Password);
            }
        }

        protected bool _RememberLoginId;
        /// <summary>
        /// 注释
        /// </summary>
        public bool RememberLoginId
        {
            get { return _RememberLoginId; }
            set
            {
                _RememberLoginId = value;
                NotifyPropertyChanged(m => m.RememberLoginId);
                Utility.CookiesUtils.SetCookie(COOKIES_KEY_REMEMBER_LOGINID, value.ToString());
            }
        }

        protected bool _RememberSession;
        /// <summary>
        /// 注释
        /// </summary>
        public bool RememberSession
        {
            get { return _RememberSession; }
            set
            {
                _RememberSession = value;
                NotifyPropertyChanged(m => m.RememberSession);
                Utility.CookiesUtils.SetCookie(COOKIES_KEY_REMEMBER_SESSION, value.ToString());
            }
        }
        #endregion

        #region LoginCommand

        private SimpleMvvmToolkit.DelegateCommand _LoginCommand = null;
        public SimpleMvvmToolkit.DelegateCommand LoginCommand
        {
            get
            {
                if (_LoginCommand == null)
                {
                    _LoginCommand = new SimpleMvvmToolkit.DelegateCommand(Login, CanExcuteLogin);
                } return _LoginCommand;
            }
            set { _LoginCommand = value; NotifyPropertyChanged(m => m.LoginCommand); }
        }

        public void Login()
        {
            if (RememberLoginId)
            {
                Utility.CookiesUtils.SetCookie(COOKIES_KEY_LOGINID, LoginId);
            }

            EIA.WCFService.AuthProxy.AuthenticationProxy proxy = new WCFService.AuthProxy.AuthenticationProxy();
            proxy.Login(LoginId, Password, (token) =>
            {
                if (string.IsNullOrEmpty(token))
                {
                    System.Windows.MessageBox.Show("登录失败！", "提示", System.Windows.MessageBoxButton.OK);
                }
                else
                {
                    Utility.CookiesUtils.SetCookie(EIA.WCFService.ClientProxy.ProxyBase.TOKEN_COOKIE_KEY, token);
                    IdentifyLoginStaff();
                }
            }, (ex) =>
            {
                System.Windows.MessageBox.Show("登录期间发生错误！", "提示", System.Windows.MessageBoxButton.OK);
            });
        }

        public bool CanExcuteLogin()
        {
            return true;
        }

        #endregion

        private void IdentifyLoginStaff()
        {
            Busy("验证身份...");
            string token = EIA.SLClient.Utility.CookiesUtils.GetCookie(EIA.WCFService.ClientProxy.ProxyBase.TOKEN_COOKIE_KEY);
            if (token == null)
            {
                Free();
            }
            else
            {
                AuthenticationProxy proxy = new AuthenticationProxy();
                proxy.GetUniqueId(token, (stf_id) =>
                {
                    if (string.IsNullOrEmpty(stf_id))
                    {
                        Free();
                    }
                    else
                    {
                        Busy("获取登录用户...");
                        EIA.Basic.BLL.ClientProxy.TStaffProxy stfProxy = new Basic.BLL.ClientProxy.TStaffProxy();
                        Dictionary<string, object> con = new Dictionary<string, object>();
                        con[TStaff.STF_ID] = stf_id;
                        stfProxy.List(con, 1, 1, (lst) =>
                        {
                            Free();
                            if (lst != null && lst.Count == 1)
                            {
                                LoginedStaff = lst[0];
                                IsShow = false;
                                SendMessage<TStaff>(EIA.SLClient.ProjectManage.Infrastructure.MessageTokens.LOGIN_STAFF_IDENTIFIED, new SimpleMvvmToolkit.NotificationEventArgs<TStaff>("", LoginedStaff));

                                List<string> simple_pwd = new List<string>();
                                simple_pwd.Add("000000");
                                simple_pwd.Add("111111");
                                simple_pwd.Add("123456");
                                simple_pwd.Add("888888");
                                if (simple_pwd.Contains(Password))
                                {
                                    SendMessage(EIA.SLClient.ProjectManage.Infrastructure.MessageTokens.CHANGE_PASSWORD, new SimpleMvvmToolkit.NotificationEventArgs());
                                    System.Windows.MessageBox.Show("您的密码过于简单，请修改密码！","提示", System.Windows.MessageBoxButton.OK);
                                }
                            }
                        }, (ex) =>
                        {
                            Free();
                        });
                    }
                }, (ex) =>
                {
                    Free();
                });
            }
        }
    }
}